package cn.qiyu5522.interceptors;

import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * ClassName: RequestIdInterceptor
 * Package: cn.qiyu5522.interceptors
 * Description:
 *
 * @Author: Tonkey
 * @Create：2024/4/9-17:43
 * @Version: v1.0
 */
@Component
public class RequestIdInterceptor implements HandlerInterceptor {
    private static final String REQUEST_ID = "requestId";


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String requestId = UUID.randomUUID().toString(); // 或者其他方式生成唯一ID
        MDC.put(REQUEST_ID, requestId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        MDC.remove(REQUEST_ID);
    }
}
